package com.common.taglibs;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * @author wq
 */
public class MyTreeTag extends TagSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Collection collection;

	private String name;

	private String scope;

	public void setCollection(Collection collection) {
		this.collection = collection;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setScope(String scope) {
		this.scope = scope;
	}

	@SuppressWarnings("unchecked")
	@Override
	public int doEndTag() throws JspException {
		StringBuffer tree = new StringBuffer();
		if(collection != null && collection.size() > 0){
			tree.append("<script type=\"text/javascript\">\n");
			tree.append(createTreeInfo((List<Map>)collection));
			tree.append("</script>\n");
			
			tree.append("<div class=\"dtree\">\n");
			tree.append("");
			tree.append("<script type=\"text/javascript\">\n");
			tree.append("<!--\n");
			tree.append("document.write(Tree);\n");
			tree.append("//-->\n");
			tree.append("</script>\n");
			tree.append("</div>\n");
		}else{
			tree.append("has no menu node. may be you have not any right!");
		}
		try {
			pageContext.getOut().println(tree.toString());
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return super.doEndTag();
	}
	
	 protected String createTreeInfo(List<Map> alist){
		if(alist == null || alist.size() == 0){
			return "";
		}
		 
	    StringBuffer contents = new StringBuffer();
	    contents.append("<!--\n");
	    contents.append(" Tree = new dTree('Tree');\n");
	    Map info =null;
	    for(int max = alist.size(),i=0;i<max;i++){
	     info = (Map)alist.get(i);
	     //define elements of array
	     contents.append("Tree.add("+info.get("id")+","+info.get("pid")+",'"+info.get("name")+"','"+info.get("url")+"','','"+info.get("target")+"');\n");
	    }
	    contents.append("//--> \n");
	   
	    return contents.toString();
	}

	public Collection getCollection() {
		return collection;
	}

	public String getName() {
		return name;
	}

	public String getScope() {
		return scope;
	}
}
